import React, { useEffect, useState } from "react";

// antd组件依赖
import { Card, Breadcrumb, Input, Space, Button, Popconfirm, Table, InputNumber, message } from 'antd';
import { HomeOutlined, UserOutlined } from '@ant-design/icons';

// hook
import { useShoppingCart } from "../../hook/shoppingCart";

const { Search } = Input;







// eslint-disable-next-line
export default () => {
  let [{ rows, eachPage, curPage, total }, { getShoppingCart, setCurPage, setEachPage, delComm, changeCount, findCart, createOrderHook }] = useShoppingCart();
  // console.log(rows, eachPage, curPage, total);


  // 表格依赖
  const columns = [
    {
      title: '购物车id',
      dataIndex: '_id',
      key: '_id',

    },
    {
      title: '用户',
      dataIndex: 'user_id',
      key: 'user_id',
      render: (text, record) => {
        return <span>{text.username}</span>
      }

    },
    {
      title: '用户Id',
      dataIndex: 'user_id',
      key: 'user_id',
      render: (text, record) => {
        return <span>{text._id}</span>
      }

    },
    {
      title: '秒杀商品',
      dataIndex: 'seckill_id',
      key: 'seckill_id',
      render: (text, record) => {
        const { name } = text.commodity_id;
        return <span>{name}</span>
      }
    },
    {
      title: '商品单价',
      key: 'unit_price',
      render: (text, record) => {
        const { Price } = text.seckill_id;
        return <span>{Price}</span>
      }
    },
    {
      title: '商品数量',
      dataIndex: 'count',
      key: 'count',
      render: (text, record) => {
        // 最大数量：限购数量
        return <InputNumber min={1} max={record.seckill_id.restricted} value={record.count} onChange={(value) => countChange(value, record._id)} />
      }
    },
    {
      title: '总价',
      key: 'price',
      render: (text, record) => {
        const totalPrice = record.seckill_id.Price * record.count;
        return <span>{totalPrice}</span>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        return (
          <Space size="middle">
            <Popconfirm title="确定删除？" okText="Yes" cancelText="No" onConfirm={() => { handleDelete(record._id) }}  >
              <Button shape="round" type="primary" danger>删除</Button >
            </Popconfirm>
          </Space>
        )
      },
    },
  ];

  // 选中需要生成订单的数据
  const [order, setOrder] = useState([]);


  // 删除确认按钮方法
  const handleDelete = async (_id) => {
    await delComm(_id);
    message.success({ content: '删除成功' });
    getShoppingCart();
  }

  // 点击修改按钮方法
  const countChange = async (count, _id) => {
    await changeCount({ count, _id });
    getShoppingCart();
  }

  // 通过用户id查找对应购物车商品
  const onSearch = async value => {
    await findCart(value);
  };


  // 点击生成订单方法
  const createOrder = async () => {
    const data = [];
    console.log(order);

    // 下单时间
    data.orderTime = new Date().toLocaleString('chinese', { hour12: false });
    data.userId = order[0].user_id._id;


    // 计算总价、为方便模糊搜索的订单名、整合购物车id
    data.searchName = ``;
    data.totalPrice = 0;
    data.shoppingCartId = order.map(item => {
      data.searchName += item.seckill_id.name
      data.totalPrice += item.seckill_id.Price * item.count;
      return item._id;
    });

    // 整合商品数据
    data.commodities = order.map(item => {
      return {
        seckill_id: item.seckill_id._id,
        commodity_id: item.seckill_id.commodity_id._id,
        count: item.count,
      }
    });
    // 状态
    data.isPaySuccess = 1;
    data.isAffirmReceive = 0;
    // isDisplay 0为默认显示，1为不显示
    data.isDisplay = 0;

    const temp = await createOrderHook(data);
    if (temp._id) {
      message.success({ content: '新增成功!' });
      // 新增成功后，此时刷新页面，已将购买的商品从购物车移出
      getShoppingCart();
    } else {
      message.error('库存不足，购买失败');
    }
  }


  // 获取购物车数据
  useEffect(() => {
    getShoppingCart()
  }, [getShoppingCart])


  return (
    <Space direction="vertical" style={{ width: "100%" }}>

      <Card >
        {/* 面包屑导航 */}
        <Breadcrumb>
          <Breadcrumb.Item href="/#/info">
            <HomeOutlined />
          </Breadcrumb.Item>
          <Breadcrumb.Item href="">
            <UserOutlined />
            <span>shoppingCart</span>
          </Breadcrumb.Item>
          <Breadcrumb.Item>shoppingCart List</Breadcrumb.Item>
        </Breadcrumb>


        <div style={{ height: 20 }}></div>

        {/* 搜索框 */}
        <Search placeholder="查询购物车内容" onSearch={onSearch} enterButton style={{ width: "300px" }} />
      </Card>

      <Card>
        {/* 购物车表格 */}
        <Table
          rowSelection={{
            type: "checkbox",
            // 表格选中行方法
            onChange: (selectedRowKeys, selectedRows) => {
              setOrder(selectedRows);
            }
          }}
          columns={columns}
          dataSource={rows}
          rowKey={(record) => record._id}
          pagination={{
            total,
            current: curPage,
            pageSize: eachPage,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['1', '2', '5'],
            onChange: (curPage, eachPage) => {
              setCurPage(curPage);
              setEachPage(eachPage);
            },

          }}
        />

        <Button type="primary" onClick={createOrder}>生成订单</Button>
      </Card>

    </Space>

  )
}